在 C++11 之前,C++ 標準是 「與線程無關」, 依賴於平台特定的 API,例如 POSIX 線程(Pthreads)或 Win32。現代 C++ 透過引入正式的 記憶體模型 以及標準化的併發 API,徹底改變了這門語言。
1. C++11 的「重大轉變」
C++11 將語言從單執行緒的抽象機器轉變為能原生理解透過 <thread> 標頭和 std::thread來實現併發執行的機制。這使多執行緒不再只是外部函式庫的議題,而是納入核心類型系統的一部分。
2. 例外保障
在併發環境中, noexcept 修飾符至關重要。它提供了一種合約,即一個函數(如執行緒的入口點)不會傳播例外。若例外逃逸出 noexcept 邊界, std::terminate() 將立即被呼叫,以防止未定義狀態的損壞。
3. 一致的資料類型
標準化包含了像 long long int (源自 C99)以及 std::filesystem等類型,確保當線程間共享時,資料寬度與系統互動在不同硬體上保持一致。
noexcept specifier in a multi-threaded application?It makes the code execute faster by disabling all memory barriers.
It prevents data races automatically.
It guarantees a function won't throw, allowing optimizations and preventing std::terminate on escape.
It forces the thread to run on a single core.
int64_t
long long int
std::atomic_int
size_t
True
False
noexcept calls a function that throws an exception?The exception is caught and ignored.
The compiler replaces it with a return 0.
The program immediately calls std::terminate().
The program pauses the thread until a debugger is attached.
Use
std::thread from the <thread> header. This abstracts the OS-level thread creation and works identically across Windows, Linux, and macOS.Use
long long int, which guarantees at least 64 bits of precision and was formally adopted into C++11 for cross-platform data width consistency.Mark the thread's entry-point lambda or function as
noexcept. This documents that the logger shouldn't throw and allows the compiler to optimize, while explicitly handling internal errors within the scope.